#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib2

class HeadRequest(urllib2.Request):
    
    def get_method(self):
        if not self.has_data():
            return 'HEAD'
        return urllib2.Request.get_method(self)

def get_http_response(http_url, referer=None, user_agent=None, timeout=10):
        """获取http详细的响应信息"""
        assert http_url.startswith('http://')
        OLD_TIMEOUT = urllib2.socket.getdefaulttimeout()
        urllib2.socket.setdefaulttimeout(timeout)
        opener = urllib2.build_opener()
    #    req.add_header('User-Agent', 
        req = HeadRequest(http_url)
    #        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')
        if referer is not None:
            req.add_header('Referer', referer)
        if user_agent is not None:
            req.add_header('User-Agent', user_agent)
        try:
            response = opener.open(req)
            response.close()
        except Exception, e:
            print e
            response = None
        urllib2.socket.setdefaulttimeout(OLD_TIMEOUT)
        return response
    
if __name__ == '__main__':
    r = get_http_response('http://bt.xdowns.com/uploadFile/2009-2/Imgsvr_Install_0.6.21.rar',
                          'http://www.xdowns.com/soft/softdown.asp?softid=37356')
#    r = get_http_response('http://127.0.0.1:8001')
    print r.headers